package cn.tukk.otherTest;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import scala.Tuple2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @program: sparkProjectNew
 * @description
 * @author: tkk fendoukaoziji
 * @create: 2019-02-28 14:56
 **/
public class TestFlatMapToPair {
    public static void main(String[] args) {
        // 创建SparkConf
        SparkConf conf = new SparkConf()
                .setAppName("AreaTop3ProductSpark").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);
        JavaRDD<String> lines = sc.textFile("wordCount");
        JavaPairRDD<String, Integer>  pairWords = lines.flatMapToPair(s -> {
            List<Tuple2<String, Integer>> returnList = new ArrayList<>();
            List<String> stringList = Arrays.asList(s.split(" "));
            Iterator<String> iter = stringList.iterator();
            while (iter.hasNext()) {
                returnList.add(new Tuple2<>(iter.next(), 1));
            }
            return returnList;
        });
        JavaPairRDD<String, Integer> result = pairWords.reduceByKey((v1, v2) -> v1 + v2);
        result.foreach(stringIntegerTuple2 -> System.out.println(stringIntegerTuple2));
        sc.stop();
    }
}
